package com.gsbelarus.gedemin.lib.ui.viewpager;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;

import com.gsbelarus.gedemin.lib.Utils;
import com.gsbelarus.gedemin.lib.ui.ArgumentsHelper;

import java.util.Calendar;
import java.util.List;

/**
 * Адаптер для view pager, отображает данные только на те даты, что есть в базе данных
 */
public class ViewPagerDateAdapter extends FragmentStatePagerAdapter {

    private int size = 1;

    private Class fragmentName;
    private ArgumentsHelper argumentsHelper;

    private List<Calendar> slidingDatesList;

    public ViewPagerDateAdapter(FragmentManager fm, Class fragmentName, ArgumentsHelper argumentsHelper, List<Calendar> slidingDatesList) {
        super(fm);
        this.fragmentName = fragmentName;
        this.argumentsHelper = argumentsHelper;
        this.slidingDatesList = slidingDatesList;
        if (!slidingDatesList.isEmpty())
            size = slidingDatesList.size();
    }

    @Override
    public Fragment getItem(int position) {
        try {
            Fragment fragment = (Fragment) fragmentName.newInstance();
            fragment.setArguments(argumentsHelper.putParams(getDate(position)));

            return fragment;
        } catch (InstantiationException e) {
            Log.d(this.getClass().getSimpleName(), e.getMessage());
        } catch (IllegalAccessException e) {
            Log.d(this.getClass().getSimpleName(), e.getMessage());
        }
        return null;
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public int getCount() {
        return size;
    }

    /**
     * @return дата по позиции
     */
    public Calendar getDate(int position) {
        return slidingDatesList.get(position);
    }

    /**
     * @return позиция по дате
     */
    public int getItemDate(int day, int month, int year) {
        Calendar date = (Calendar) slidingDatesList.get(0).clone();

        /** создаем calendar с входными параметрами (day, month, year) */
        date.set(Calendar.YEAR, year);
        date.set(Calendar.MONTH, month - 1);
        date.set(Calendar.DAY_OF_MONTH, day);
        Utils.initCalendarFields(date, argumentsHelper.slidingDate, 1);

        Calendar bufDate;
        for (int i = 0; i < size; i++) {
            bufDate = getDate(i);
            Utils.initCalendarFields(bufDate, argumentsHelper.slidingDate, 1);
            if (date.compareTo(bufDate) == 0)
                return i;
        }
        return size - 1;
    }

    public int getSize() {
        return size;
    }
}
